package com.ins1st.plus.config.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: ins1st-plus
 * @description: shiro配置类
 * @author: coderSun
 * @create: 2019-09-09 11:53
 **/
@Configuration
public class ShiroConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${ins1st.seesion-redis}")
    private boolean isRedisSeesion;


    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/doLogin", "anon");
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        ShiroRedisConfig shiroRedisConfig = new ShiroRedisConfig();
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        if (isRedisSeesion) {
            defaultSecurityManager.setCacheManager(shiroRedisConfig.cacheManager(host, port, password));
            defaultSecurityManager.setSessionManager(shiroRedisConfig.sessionManager(host, port, password));
        }
        defaultSecurityManager.setRealm(shiroRealm());
        return defaultSecurityManager;
    }


    @Bean
    public ShiroRealm shiroRealm() {
        return new ShiroRealm();
    }
}
